import { useRef, useMemo } from "react";
import eventExtension from '@/pages/utils/eventExtension'
import { useVisionStore, useForceUpdate } from '@/pages/index'
import OpNode from '@/pages/Vision2/Node'

const menumove = 'menumove'

export default function MenuMove(props: any) {
  let { children, comCode } = props
  const store = useVisionStore()
  const { event, components } = store
  const isDragP:any = useRef(null)
  const ref: any = useRef(null);
  const forceUpdate = useForceUpdate()
  const currentDomRect = useMemo(() => ref.current?.getBoundingClientRect() || {}, [ref.current]);
  const ItStyleP = useRef({
    x: currentDomRect?.left || 0,
    y: currentDomRect?.top || 0,
    w: 0,
    h: 0,
  });

  useMemo(() => {
    event.addQueue('mouseup', {
      code: menumove,
      callBack: () => {
        if (ref.current) {
          isDragP.current = false
          ItStyleP.current = { x: 0, y: 0, w: 0, h: 0 };
          event.handleToolIntercept('mousemove', menumove, true)
          event.handleToolIntercept('mouseup', menumove, true)
          event.handleToolIntercept('mousemove', 'DynamicDiscern', true)
          event.handleToolIntercept('mouseup', 'DynamicDiscern', true)
          event.handleToolIntercept('mousemove', 'DynamicDrop', true)
          event.handleToolIntercept('mouseup', 'DynamicDrop', true)
          forceUpdate();
        }
      }
    });
    event.addQueue('mousemove', {
      code: menumove,
      callBack: (e: any) => {
        if (ref.current) {
          isDragP.current = true
          ItStyleP.current = {
            ...ItStyleP.current,
            y: e.clientY - 10,
            x: e.clientX - 50,
          };
          forceUpdate();
        }
      },
    });
  }, []);



  const onMouseDown = (e: any) => {
    e.preventDefault();
    ItStyleP.current = {
      w: ref.current?.clientWidth,
      h: ref.current?.clientHeight,
      y: e.clientY - 10,
      x: e.clientX - 50,
    };
    // console.log(comCode, components)
    // let planAction = components[comCode].planAction || {}
    const currentOpNode = new OpNode({code: comCode});

    store.moveOpNode = currentOpNode

    // event 的 识别区的 拦截去掉
    event.handleToolIntercept('mousemove', menumove, false)
    event.handleToolIntercept('mouseup', menumove, false)
    event.handleToolIntercept('mousemove', 'DynamicDiscern', false)
    event.handleToolIntercept('mouseup', 'DynamicDiscern', false)
    event.handleToolIntercept('mousemove', 'DynamicDrop', false)
    event.handleToolIntercept('mouseup', 'DynamicDrop', false)
  };


  return (
    <div onMouseDown={onMouseDown} className="dynamicMenuMove" ref={ref}>
      <div
        className="dynamicMenuMoveData"
        style={eventExtension.modifyStyleTsForm(ItStyleP.current)}
        hidden={!isDragP.current}
      >
        {children}
      </div>
      {children}
    </div>
  );
}